package com.vcc.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vcc.core.exception.NotFoundException;
import com.vcc.core.util.AesUtil;
import com.vcc.data.entity.*;
import com.vcc.data.mapper.ReserveCardMapper;
import com.vcc.service.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReserveCardServiceImpl extends ServiceImpl<ReserveCardMapper, ReserveCard> implements ReserveCardService {

    private static final Logger logger = LoggerFactory.getLogger(ReserveCardServiceImpl.class);


    @Autowired
    private WalletService walletService;
    @Autowired
    private WalletDetailService walletDetailService;
    @Autowired
    private UserCardService userCardService;
    @Autowired
    private CardOrderService cardOrderService;

    @Override
    public Long countByCardId(Long cardId) {
        return queryChain().eq(ReserveCard::getCardId, cardId).eq(ReserveCard::getStatus, 0).count();
    }

    @Override
    public Long countByCardIdAndStatus(Long cardId, Integer status) {
        return queryChain().eq(ReserveCard::getCardId, cardId).eq(ReserveCard::getStatus, status).count();

    }

    @Override
    public ReserveCard getByPpCardId(String ppCardId) {
        return queryChain().eq(ReserveCard::getPpCardId, ppCardId).oneOpt().orElseThrow(() -> new NotFoundException("没有当前卡种记录"));
    }

    @Override
    public Boolean openCard(User user, BigDecimal rechargeAmount, CardType card, Integer count, String remark, Wallet wallet, Long cardholderId) {
//        List<ReserveCard> list;
//        synchronized (card.getId()) {
//            //拿到状态为0的剩余卡数
//            Long reserveCardCount = countByCardId(card.getId());
//            if (reserveCardCount <= 50) {
//                return false;
//            }
//            if (reserveCardCount < count) {
//                return false;
//            }
//            //根据数量拿数据
//            list = mapper.findAllByCardIdAndCount(card.getId(), count);
//            updateChain()
//                    .set(ReserveCard::getStatus, 1)
//                    .eq(ReserveCard::getStatus, 0)
//                    .in(ReserveCard::getId, list.stream().map(ReserveCard::getId).collect(Collectors.toList()))
//                    .update();
//        }
//        List<Long> ids = new ArrayList<>();
//        try {
//            for (ReserveCard reserveCard : list) {
//                String cardNumber = AesUtil.decrypt(reserveCard.getCardNumber());
//                String cvc = AesUtil.decrypt(reserveCard.getVcc());
//                String expiry = AesUtil.decrypt(reserveCard.getExpiry());
//                //优先扣除余额
//                BigDecimal openCardResultAmount = walletService.subtractUsableQuotaById(wallet.getId(), card.getAmount(), 2, false);
//                cardOrderService.openCard(
//
//                )
//                walletDetailService.openCard(userCard.getId(),user, cardNumber, reserveCard.getOrderId(), remark, card.getAmount(), openCardResultAmount, "", wallet.getCurrencyId(), user.getId());
//
//                //记录明细
//                UserCard userCard = new UserCard();
//                userCard.setCardNumber(cardNumber);
//                userCard.setCardNumberLastFour(cardNumber.substring(cardNumber.length() - 4));
//                userCard.setVcc(cvc);
//                userCard.setExpiry(expiry);
//                userCard.setRequestDate(new Date());
//                userCard.setOrderId(reserveCard.getOrderId());
//                userCard.setCardTypeId(card.getId());
//                userCard.setUserId(user.getId());
//                userCard.setChannelCardId(reserveCard.getPpCardId());
//                userCard.setChannelCode(card.getCode());
//                userCard.setCurrencyCode(card.getCurrencyCode());
//                userCard.setCurrencyName(card.getCurrencyName());
//                userCard.setCardType(card.getCardLabel());
//                userCard.setUsableQuota(BigDecimal.valueOf(0));
//                userCard.setRemark(remark);
//                userCard.setCardStatus("ACTIVE");
//                userCard.setSumCount(0);
//                userCard.setSuccessCount(0);
//                userCard.setErrorCount(0);
//                userCard.setSumAmount(BigDecimal.valueOf(0));
//                userCard.setSuccessAmount(BigDecimal.valueOf(0));
//                userCard.setErrorAmount(BigDecimal.valueOf(0));
//                userCard.setCardholderId(cardholderId);
//                userCardService.save(userCard);
//
//                removeById(reserveCard.getCardId());
//                ids.add(reserveCard.getId());
////                if (Objects.equals(rechargeAmount.compareTo(BigDecimal.valueOf(0)), 1)) {
////                    //此处会抛出异常，但是可以作为充值失败处理，直接中断
////                    pingPongComponent.recharge(reserveCard.getOrderId(), remark, userCard, rechargeAmount);
////                }
//            }
//        } catch (Exception e) {
//            logger.error("储备卡开卡失败", e);
//            //出现异常需要补偿
//            for (ReserveCard reserveCard : list) {
//                for (Long id : ids) {
//                    //排除已处理的
//                    if (!reserveCard.getId().equals(id)) {
//                        updateChain().set(ReserveCard::getStatus, 0).eq(ReserveCard::getId, reserveCard.getId()).update();
//                    }
//                }
//            }
//            throw e;
//        }
        return true;
    }


}
